import {Component} from '@angular/core';
import {GnMessageService, GnTableButton, GnTableComponent} from 'geminis-ng';
import {FormListComponent} from "./form-list.component";
import {HttpClient} from "@angular/common/http";

@Component({
  selector: 'workflow-model-table-button',
  template: `
    <button nz-button [disabled]="!table?.isSingleSelected" (click)="export()">
      <i nz-icon nzIconfont="download"></i>导出
    </button>
    <nz-upload [nzShowUploadList]="false" (nzChange)="stateChange($event)"
               [nzAction]="'/api/everydata/forms/import/' + this.formList.category||''">
      <button nz-button>
        <i nz-icon nzIconfont="upload"></i>导入
      </button>
    </nz-upload>
  `,
  styles: [':host{order: 210;}', 'nz-upload{display: inline-block}']
})
@GnTableButton('everydata-form')
export class FormListButtonComponent {

  table?: GnTableComponent;

  constructor(public formList: FormListComponent,
              private http: HttpClient,
              private messageService: GnMessageService) {
  }

  export(): void {
    this.http.get('/api/everydata/forms/' + this.table?.selectedKey, {
      responseType: 'blob'
    }).subscribe(data => {
      const a = document.createElement('a')
      const objectUrl = URL.createObjectURL(data);
      a.href = objectUrl;
      a.download = this.table?.selectedOne.name + '.json';
      a.click();
      URL.revokeObjectURL(objectUrl);
    }, error => {
      this.messageService.warn('导出错误');
    });
  }

  stateChange(state: any): void {
    if (state.type === 'success') {
      this.messageService.success('导入成功');
      this.table?.loadData();
    }
  }
}
